package cn.easyplatform.studio.utils;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;

import java.io.File;

/**
 * @Author Zeta
 * @Version 1.0
 */
public class AppTemplateUtil {
    //通过传入项目名获取app路径
    public String getAppTemplatePath(String Name) {
        return getEngineProjectPath() + File.separator + getAppTemplatePath() + File.separator + Name;
    }

    private String getEngineProjectPath() {
        String relativePath = StudioApp.getAppPath();
        relativePath = getAppRealPath(relativePath);
        return System.getProperty("catalina.home") + File.separator + "webapps" + File.separator + relativePath;
    }

    private String getAppTemplatePath() {
        String relativePath = StudioApp.getAppTemplatePath();
        if (Strings.isBlank(relativePath))
            relativePath = "/WEB-INF/template";
        relativePath = getAppRealPath(relativePath);
        return relativePath;
    }

    private String getAppRealPath(String path) {
        if (path.startsWith("/") || path.startsWith("\\")) {
            path = path.substring(1, path.length());
        }
        if (path.endsWith("/") || path.endsWith("\\")) {
            path = path.substring(0, path.length() - 1);
        }
        if (path.indexOf("/") != -1 || path.indexOf("\\") != -1) {
            if (path.indexOf("/") != -1) {
                if (File.separator.equals("\\"))
                    path = path.replaceAll("/", "\\\\");
                else
                    path = path.replaceAll("/", File.separator);
            }
            if (path.indexOf("\\") != -1) {
                if (File.separator.equals("\\"))
                    path = path.replaceAll("\\\\", "\\\\");
                else
                    path = path.replaceAll("\\\\", File.separator);
            }
        }
        return path;
    }
}
